﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Rampant.Muninn
{
    public class RssFeedModel
    {
        private XDocument _rssDoc;
        private Uri _feedSource;
        private List<RssChannel> _channels;

        public XDocument RawFeed { get { return _rssDoc; } }
        public List<RssChannel> Channels
        {
            get
            {
                if (_channels == null)
                {
                    _channels = new List<RssChannel>(from c in _rssDoc.Descendants("channel")
                                                     select new RssChannel(c));
                } 
                return _channels;
            }
        }

        public RssFeedModel(string feedSource)
        {
            _rssDoc = GetFeed(new Uri(feedSource));
        }

        public RssFeedModel(Uri feedSource)
        {
            _rssDoc = GetFeed(feedSource);
        }

        public void Refresh()
        {
            _rssDoc = GetFeed(_feedSource);
            _channels = null;
        }

        private XDocument GetFeed(Uri feedSource)
        {
            _feedSource = feedSource;
            // Pulldown the feed and load the XML content into a Linq XDocument
            _rssDoc = XDocument.Load(feedSource.ToString());
            return _rssDoc;
        }        
    }
}
